package com.bwie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.config.OSSFileUtil;
import com.bwie.mapper.*;
import com.bwie.pojo.*;
import com.bwie.service.GoodService;
import com.bwie.service.IUserService;
import com.bwie.util.R;
import com.bwie.vo.GoodVo;
import com.bwie.vo.Option;
import com.bwie.vo.PageVo;
import com.bwie.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program: day0513-monthlx
 * @ClassName GoodServiceImpl
 * @description:
 * @author: 段阳
 * @create: 2024-05-14 15:27
 **/
@Service
@Transactional
public class GoodServiceImpl implements GoodService {

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private GoodImgMapper goodImgMapper;

    @Autowired
    private GoodInfoMapper goodInfoMapper;

    @Autowired
    private GoodMsgMapper goodMsgMapper;

    @Autowired
    private GoodTypeMapper goodTypeMapper;

    @Autowired
    private SbuMapper sbuMapper;

    @Autowired
    private SpecMapper specMapper;

    @Autowired
    private TacticsMapper tacticsMapper;

    @Autowired
    private OSSFileUtil ossFileUtil;


    @Autowired
    private RedissonClient redissonClient;


    @Override
    public R findGoodsList(PageVo pageVo) {
        Page<Goods> goodsPage = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if (!StringUtils.isBlank(pageVo.getKey())){
            wrapper.lambda().like(Goods::getGoodName,pageVo.getKey());
        }

        if (pageVo.getTid1() !=null){
            wrapper.lambda().eq(Goods::getTid1,pageVo.getTid1());
        }
        if (pageVo.getTid2() !=null){
            wrapper.lambda().eq(Goods::getTid2,pageVo.getTid2());
        }
        if (pageVo.getGoodStatus()!=null){
            wrapper.lambda().eq(Goods::getGoodStatus,pageVo.getGoodStatus());
        }
        wrapper.lambda().orderByDesc(Goods::getRecom);
        Page<Goods> page = goodMapper.selectPage(goodsPage, wrapper);

        List<Goods> records = page.getRecords();
        for (Goods record : records) {
            List<GoodImg> goodImgs = goodImgMapper.selectList(new QueryWrapper<GoodImg>().lambda().eq(GoodImg::getGoodId, record.getId()));
            record.setImgList(goodImgs);
            GoodMsg goodMsg = goodMsgMapper.selectOne(new QueryWrapper<GoodMsg>().lambda().eq(GoodMsg::getGoodId, record.getId()));
            record.setGoodsMsg(goodMsg);
            GoodInfo goodInfo = goodInfoMapper.selectOne(new QueryWrapper<GoodInfo>().lambda().eq(GoodInfo::getGoodId, record.getId()));
            record.setGoodsInfo(goodInfo);
            List<Spec> specList = specMapper.selectList(new QueryWrapper<Spec>().lambda().eq(Spec::getGoodId, record.getId()));
            for (Spec spec : specList) {
                List<Sbu> sbus = sbuMapper.selectList(new QueryWrapper<Sbu>().lambda().eq(Sbu::getSpecId, spec.getId()));
                spec.setSbuList(sbus);
            }
            record.setSpecsList(specList);
            List<Tactics> tactics = tacticsMapper.selectList(new QueryWrapper<Tactics>().lambda().eq(Tactics::getGoodId, record.getId()));
            record.setTactics(tactics);
        }
        PageVo pageVo1 = new PageVo(pageVo.getPageNum(), pageVo.getPageSize(), (int) page.getTotal(), null, null, null, null, records);


        return R.success("",pageVo1);
    }

    @Override
    public R findTypeList(Integer pid) {
        List<GoodType> goodTypes = goodTypeMapper.selectList(new QueryWrapper<GoodType>().lambda().eq(GoodType::getPid, pid));
        return R.success("",goodTypes);
    }

    @Override
    public R uploadPhoto(MultipartFile file) throws IOException {
        String s = ossFileUtil.uploadFile(file);
        return R.success("",s);
    }

    @Override
    public R uploadVideo(MultipartFile file) throws IOException {
        String s = ossFileUtil.uploadFileByBreakingPoint(file);
        return R.success("",s);
    }

    @Override
    public R addNewGood(GoodVo goodVo) {

        Goods goods = BeanUtil.toBean(goodVo, Goods.class);
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setGoodStatus(true);
        goods.setRecom(false);
        goodMapper.insert(goods);

        Integer id = goods.getId();
        GoodMsg goodMsg = new GoodMsg();
        goodMsg.setGoodId(id);
        goodMsg.setGoodMsg(goodVo.getGoodMsg());
        goodMsgMapper.insert(goodMsg);

        GoodInfo goodInfo = BeanUtil.toBean(goodVo.getGoodInfo(), GoodInfo.class);
        goodInfo.setGoodId(id);
        goodInfoMapper.insert(goodInfo);

        List<String> imgPathList = goodVo.getImgPathList();
        for (String s : imgPathList) {
            GoodImg goodImg = new GoodImg();
            goodImg.setGoodId(id);
            goodImg.setImgPath(s);
            goodImgMapper.insert(goodImg);
        }

        List<Spec> specList = goodVo.getSpecList();
        for (Spec spec : specList) {
            Spec spec1 = new Spec();
            spec1.setGoodId(id);
            spec1.setSpecName(spec.getSpecName());
            specMapper.insert(spec1);
            Integer id1 = spec1.getId();
            List<Sbu> sbuList = spec.getSbuList();
            for (Sbu sbu : sbuList) {
                Sbu sbu1 = new Sbu();
                sbu1.setGoodPhoto(goodVo.getGoodPhoto());
                sbu1.setSpecName(spec.getSpecName());
                sbu1.setSpecId(id1);
                sbu1.setSubInfo(sbu.getSubInfo());
                sbuMapper.insert(sbu1);
            }

        }


        return R.success("添加成功");
    }

    @Override
    public R upGoodRecom(Integer id) {
        RLock lock = redissonClient.getLock("good"+id);
        try {
            lock.lock();
            Goods goods = goodMapper.selectById(id);
            UpdateWrapper<Goods> wrapper = new UpdateWrapper<>();
            if (goods.getRecom()){
                goodMapper.update(goods,wrapper.lambda().set(Goods::getRecom,false).eq(Goods::getId,goods.getId()));
            }else {
                goodMapper.update(goods,wrapper.lambda().set(Goods::getRecom,true).eq(Goods::getId,goods.getId()));
            }

            return R.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (lock.isLocked()||lock.isHeldByCurrentThread()){
                lock.unlock();
            }

        }
        return R.error(500,"操作失败");
    }

    @Override
    public R upTacticStatus(Integer id) {
        Tactics tactics = tacticsMapper.selectById(id);
        UpdateWrapper<Tactics> wrapper = new UpdateWrapper<>();
        if (tactics.getTacticsStatus()){
            tacticsMapper.update(tactics,wrapper.lambda().set(Tactics::getTacticsStatus,false).eq(Tactics::getId,tactics.getId()));
        }else {
            tacticsMapper.update(tactics,wrapper.lambda().set(Tactics::getTacticsStatus,true).eq(Tactics::getId,tactics.getId()));
        }
        System.out.println("123");
        System.out.println("123");
        System.out.println("123");
        System.out.println("123");
        System.out.println("123");
        System.out.println("123");
        return R.success("操作成功");
    }

    @Override
    public R addNewTactic(Tactics tactics) {
        tacticsMapper.insert(tactics);
        return R.success("添加成功");
    }

    @Autowired
    private CityMapper cityMapper;
    @Override
    public R typeList() {
        ArrayList<Option> options = new ArrayList<>();
        List<City> cities = cityMapper.selectList(new QueryWrapper<City>().lambda().eq(City::getPid, 0));
        for (City city : cities) {
            Option option = new Option(city.getId(), city.getName());
            List<City> citie2 = cityMapper.selectList(new QueryWrapper<City>().lambda().eq(City::getPid, city.getId()));
            treeList(citie2,option);
            options.add(option);

        }
        return R.success("",options);
    }

    @Autowired
    private IUserService iUserService;

    @Override
    public R getVCode() throws IOException {
        UserVo userVo = new UserVo();
        userVo.setMobile("18634472015");
        R vCode = iUserService.vCode(userVo);
        String s = JSON.toJSONString(vCode.getData());
        System.out.println("s=================="+s);

        return R.success("",s);
    }


    public Option treeList(List<City> list,Option option){

        for (City city : list) {
            List<City> cities = cityMapper.selectList(new QueryWrapper<City>().lambda().eq(City::getPid, city.getId()));

            if (cities.size()<1){
                HashMap<String, Object> map = new HashMap<>();
                map.put("id",city.getId());
                map.put("label",city.getName());
                option.addChild(map);
            }else {
                Option option1 = new Option(city.getId(), city.getName());
                option.addChild(option1);
                treeList(cities,option1);
            }
        }
        return option;

    }
}